<!-- 商品编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="1000"
    :model-value="modelValue"
    :title="isUpdate ? '修改商品' : '添加商品'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="图片" prop="images">
        <image-upload :limit="100" v-model="form.images" />
      </el-form-item>
      <el-form-item label="所属商家" prop="seller_id">
        <el-select v-model="form.seller_id">
          <el-option
            v-for="item in sellerList"
            :key="item.id"
            :value="item.id"
            :label="item.title"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="cate_id">
        <el-radio-group v-model="form.cate_id">
          <el-radio value="1" :label="1">酒店民宿</el-radio>
          <el-radio value="2" :label="2">超值团购</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="商品标签">
        <el-input v-model="form.tags" placeholder="" />
      </el-form-item>
      <el-form-item label="推荐奖励" prop="share_bouns">
        <el-input v-model="form.share_bouns" style="width: 200px" />
      </el-form-item>
      <el-form-item label="实际价格" prop="price">
        <el-input v-model="form.price" style="width: 200px" />
      </el-form-item>
      <el-form-item label="原价" prop="sales_price">
        <el-input v-model="form.sales_price" style="width: 200px" />
      </el-form-item>
      <el-form-item label="推送消息" prop="sales_price">
        <el-radio-group v-model="form.message">
          <el-radio value="1" :label="1">是</el-radio>
          <el-radio value="0" :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="图文详情" prop="content">
        <tinymce-editor ref="editorRef" :init="config" v-model="form.content" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import { pageMallSeller, updateGoods } from '@/api/mall';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import axios from 'axios';
  import { getToken } from '@/api/qiniu';
  import { Base64 } from 'js-base64';

  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 编辑器配置 */
  const config = ref({
    height: 520,
    plugins:
      'code preview fullscreen searchreplace link autolink image media table codesample lists advlist charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
    toolbar:
      'fullscreen preview code | image | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link media emoticons charmap anchor pagebreak codesample | ltr rtl',
    images_upload_handler: (blobInfo, success, error) => {
      const file = blobInfo.blob();
      console.log(file, '是什么');
      uploadQiniu(file)
        .then((res) => {
          let url = imagesUrl.value + res.key;
          success(url);
        })
        .catch((e) => {
          error(e);
        });
      // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
    }
  });

  /** 编辑器 */
  const editorRef = ref(null);

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    title: '',
    tags: '',
    share_bouns: '',
    images: '',
    price: '',
    sales_price: '',
    cate_id: 1,
    content: '',
    message: 0
  });

  /** 表单验证规则 */
  const rules = reactive({
    seller_id: [
      {
        required: true,
        message: '请选择商品所属商家',
        type: 'integer',
        trigger: 'blur'
      }
    ],
    title: [
      {
        required: true,
        message: '请输入商品名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入价格',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      var requestData = Object.assign({}, form);
      requestData.content = Base64.encode(requestData.content);
      updateGoods(requestData)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch(() => {
          loading.value = false;
        });
    });
  };
  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  // 七牛
  const uploadUrl = ref('');
  const imagesUrl = ref('');
  /** 上传七牛用到的参数 */
  const postData = ref({
    token: '',
    key: '',
    file: {}
  });
  const getQiniuToken = () => {
    getToken({})
      .then((res) => {
        postData.value.token = res.token;
        uploadUrl.value = res.uploadUrl;
        imagesUrl.value = res.imagesUrl;
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const uploadQiniu = async (request) => {
    const promise = new Promise((resolve, reject) => {
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      };
      const filePath = request.name;
      // 获取最后一个.的位置
      var index = filePath.lastIndexOf('.');
      // 获取后缀
      var ext = filePath.substr(index + 1);
      // 输出结果
      const key = `${new Date().getTime()}${Math.floor(
        Math.random() * 100
      )}.${ext}`; // 自定义文件名
      console.log(request);
      const fd = new FormData();
      fd.append('file', request);
      fd.append('token', postData.value.token);
      fd.append('key', key);
      // console.log(this.axios)
      axios
        .post(uploadUrl.value, fd, config)
        .then((res) => {
          if (res.status === 200 && res.data) {
            resolve(res.data);
          } else {
            reject(res);
          }
        })
        .catch((err) => {
          console.log(err);
          EleMessage.error({
            message: `上传失败[${err.status}]`,
            duration: 2000
          });
        });
    });
    return promise;
  };
  getQiniuToken();

  /** 租户数据 */
  const sellerList = ref([]);

  /** 获取租户数据 */
  pageMallSeller({ page: 1, limit: 9999999 })
    .then((res) => {
      sellerList.value = res.list;
      // console.log(res);
      // console.log(form.site_id);
      // assignFields({
      //   site_id: res[0].site_id
      // });
    })
    .catch((e) => {
      EleMessage.error(e.message);
    });

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.data) {
          assignFields(props.data);
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
